package com.smh.hmdianping.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author shiminghui
 * @date 2025/3/28 13:05
 * @description: 全局id生成器
 */
@Component
public class RedisIdWorker {

    private final long BEGIN_TIMESTAMP = 1735689600L;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
        long second = localDateTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }

    public long nextId(String prefix) {
        // 获取当前时间戳
        long currentTimeStamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp = currentTimeStamp - BEGIN_TIMESTAMP;
        // 获取序列号
        // 1.获取当前日期，精确到天
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.自增长
        String key = "icr" + ":" + format + ":" + prefix;
        long increment = redisTemplate.opsForValue().increment(key);
        // 3.组合
        return timestamp << 32 | increment;
    }


}
